<?php

use TpAmis\Renderers\BaseApi;
use TpAmis\Renderers\BaseRenderer;
use TpAmis\util\AmisBaseApi;

if (! function_exists('amis')) {
    /**
     * @param $type
     *
     * @return \TpAmis\Renderers\Amis | \TpAmis\Renderers\Component
     */
    function amis($type = null)
    {
        if (filled($type)) {
            return \TpAmis\Renderers\Component::make()->setType($type);
        }

        return \TpAmis\Renderers\Amis::make();
    }
}
if (! function_exists('filled')) {
    /**
     * Determine if a value is "filled".
     *
     * @param  mixed  $value
     * @return bool
     */
    function filled($value)
    {
        return ! blank($value);
    }
}

if (! function_exists('blank')) {
    /**
     * Determine if the given value is "blank".
     *
     * @param  mixed  $value
     * @return bool
     */
    function blank($value)
    {
        if (is_null($value)) {
            return true;
        }

        if (is_string($value)) {
            return trim($value) === '';
        }

        if (is_numeric($value) || is_bool($value)) {
            return false;
        }

        if ($value instanceof Countable) {
            return count($value) === 0;
        }

        return empty($value);
    }
}

if (! function_exists('getCurrentURL')) {

    /**
     * 获取当前URL
     * @return string
     */
    function getCurrentURL()
    {
        $url = 'http';
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
            $url .= 's';
        }
        $url .= '://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $url .= $_SERVER['QUERY_STRING'];
        return $url;
    }
}

if (! function_exists('this_method')) {

    function this_method($this_method)
    {
        return explode('::', $this_method)[1];
    }
}
if (! function_exists('get_fun_args')) {
    /**
     * Summary of get_fun_args
     * @param mixed $className
     * @param mixed $functionName
     * @param mixed $args
     * @return array
     */
    function get_fun_args($className, $functionName, $args = [])
    {
        $reflection = new ReflectionMethod($className, $functionName);
        $parameters = $reflection->getParameters();
        $paramNames = [];
        foreach ($parameters as $key => $param) {
            $paramNames[$param->name] = isset($args[$key]) ? $args[$key] : null; // 使用参数名作为关联数组的键
        }
        return $paramNames;
    }
}



if (! function_exists('getUrlQuery')) {

    /**
     * 将参数变为字符串
     * @param array $array_query
     * @return string
     */
    function getUrlQuery($array_query = [])
    {
        $tmp = array();
        foreach ($array_query as $k => $param) {
            $tmp[] = $k.'='.$param;
        }
        $params = implode('&', $tmp);
        return $params;
    }
}

if (! function_exists('authAmis')) {
    /**
     * 验证权限 自行实现AmisUserAuth函数
     * @param mixed $actionOrUrl
     * @return bool
     */
    function authAmis($actionOrUrl)
    {
        if (is_object($actionOrUrl) && $actionOrUrl instanceof BaseRenderer) {

            $node = extractUrlsFromJson($actionOrUrl);
            if (empty($node)) {
                return false;
            }
            return function_exists('AmisUserAuth') ? AmisUserAuth($node[0]) : true;

        } else {
            return false;
        }
    }
    function extractUrlsFromJson($data = [])
    {
        // 将数据转换为字符串以便进行正则匹配
        $dataString = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        // 正则表达式匹配URL路径
        $pattern = '/https?:\/\/[^\s"]+|[a-zA-Z0-9\-._~:\/?#\[\]@!$&\'()*+,;=]+\/[^\s"]*/';
        preg_match_all($pattern, $dataString, $matches);

        // 返回匹配到的URL路径数组
        return $matches[0];
    }

}

if (! function_exists('adminUrl')) {
    /**
     * 生成URL
     * @param string $url
     * @param array $query
     * @param mixed $suffix
     * @param mixed $domain
     * @return string
     */
    function adminUrl(string $url = '', array $query = [], $suffix = false, $domain = false): string
    {

        return AmisBaseApi::make()->adminUrl($url, $query, $suffix, $domain);
    }
}
if (! function_exists('BaseApiDelete')) {

    /**
     * 删除接口
     * @param string $thinkUrl thinkphp路由地址
     * @param array $query 请求参数
     * @param array $data  请求数据
     * @param mixed $type 提交类型：json   form-data    form
     * @return BaseApi
     */
    function BaseApiDelete(string $thinkUrl = '', array $query = [], $data = [], $type = 'form'): BaseApi
    {
        return AmisBaseApi::make()->amisBaseApi($thinkUrl, 'delete', $query, $data, $type);
    }
}
if (! function_exists('BaseApiPut')) {
    /**
     * 修改接口
     * @param string $thinkUrl thinkphp路由地址
     * @param array $query 请求参数
     * @param array $data  请求数据
     * @param mixed $type 提交类型：json   form-data    form
     * @return BaseApi
     */
    function BaseApiPut(string $thinkUrl = '', array $query = [], $data = [], $type = 'form'): BaseApi
    {
        return AmisBaseApi::make()->amisBaseApi($thinkUrl, 'put', $query, $data, $type);
    }
}
if (! function_exists('BaseApiPost')) {

    /**
     * 添加接口
     * @param string $thinkUrl thinkphp路由地址
     * @param array $query 请求参数
     * @param array $data  请求数据
     * @param mixed $type 提交类型：json   form-data    form
     * @return BaseApi
     */
    function BaseApiPost(string $thinkUrl = '', array $query = [], $data = [], $type = 'form'): BaseApi
    {
        return AmisBaseApi::make()->amisBaseApi($thinkUrl, 'post', $query, $data, $type);
    }
}
if (! function_exists('BaseApiGet')) {
    /**
     * 获取接口
     * @param string $thinkUrl thinkphp路由地址
     * @param array $query 请求参数
     * @param mixed $type 提交类型：json   form-data    form
     * @return BaseApi
     */
    function BaseApiGet(string $thinkUrl = '', array $query = [], $type = 'form'): BaseApi
    {
        return AmisBaseApi::make()->amisBaseApi($thinkUrl, 'get', $query, [], $type);
    }
}
if (! function_exists('BaseApi')) {
    /**
     * API接口
     * @param string $thinkUrl thinkphp路由地址
     * @param string $method 请求方法
     * @param array $query 请求参数
     * @param array $data  请求数据
     * @param mixed $type 提交类型：json   form-data    form
     * @return BaseApi
     */
    function amisBaseApi(string $thinkUrl = '', string $method = 'post', array $query = [], $data = [], $type = 'form'): BaseApi
    {
        return AmisBaseApi::make()->amisBaseApi($thinkUrl, $method, $query, $data, $type);
    }

}

if (! function_exists('getDomain')) {
    function getDomain()
    {
        $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
        return $scheme."://".$_SERVER['HTTP_HOST'];
    }
}
if (! function_exists('arrayToCss')) {

    function arrayToCss(array $styles, string $selector): string
    {
        // 检查输入是否为数组
        if (! is_array($styles)) {
            return "Invalid input: not an array";
        }

        // 开始构建CSS字符串
        $css = "$selector {\n";

        // 遍历数组，将每个键值对转换为CSS属性和值
        foreach ($styles as $property => $style) {
            if (is_array($style)) {
                // 如果值是数组，则递归调用函数
                $childSelector = "$selector $property";
                $css .= arrayToCss($style, $childSelector);
            } else {
                // 将PHP数组键名中的下划线转换为CSS属性名中的连字符
                $cssProperty = str_replace('_', '-', $property);
                $css .= "    $cssProperty: $style;\n";
            }
        }

        // 结束CSS字符串
        $css .= "}\n";

        return $css;
    }
}
if (! function_exists('arrayToCsses')) {

    function arrayToCsses(array $styles): string
    {
        // 检查输入是否为数组
        if (! is_array($styles)) {
            return "Invalid input: not an array";
        }

        // 开始构建CSS字符串
        $css = "";
        // 遍历数组，将每个键值对转换为CSS属性和值
        foreach ($styles as $property => $style) {
            $css .= arrayToCss($style, $property);
        }
        // 结束CSS字符串
        $css .= "\n";

        return $css;
    }
}
